<template>
	<view class="page-wrapper" v-if="config.config && tabbar && tabbar.list && tabbar.list[0].pagePath == '/pages/plat_menu/index'">
		<!-- #ifdef MP-WEIXIN -->
		<collectMiniapp :appScene="scene"></collectMiniapp>
		<!-- #endif -->	
		<tabbar :tabbar="tabbar" @returnTop="returnTop"></tabbar>
		<view :style="'height:100%;overflow-x:hidden;padding-bottom:' + account_height + 'px'">
			<indexTemplate
				ref='homeBox'
				:options="options"
				:showBackIcon="showBackIcon"
				:openDoll="openDoll"
				:scrollToTop = "scrollToTop"
				@openDoor="openDoor"
				@setTabbar="setTabbar"
			></indexTemplate>
		</view>
		
		
		<view class="aui-poster" v-if="SHOW" :class="{
			'aui-poster-in': FADE==1,
			'aui-poster-out': FADE==0}"
		>
			<view class="aui-mask" v-if="poster.mask" @touchmove.stop.prevent data-type="close" @click.stop="poster.maskTapClose ? _clickFn($event) : ''"></view>
			<view class="aui-poster-main">
				<img class="aui-poster-img" mode="widthFix" :src="poster.image" data-type="main" @click.stop="_clickFn($event)">
				<img class="aui-poster-close" mode="widthFix" data-type="close" @click.stop="_clickFn($event)" src="https://xbjz1.oss-cn-beijing.aliyuncs.com/upload/default/gz-close.png">
			</view>
		</view>

	</view>
</template>
 
<script>

import common from '../../utils/common.js'
import indexTemplate from '../common/index_template.vue';
import collectMiniapp from '../../appComponent/platcommon/collectMiniapp.vue';

var systemInfo = wx.getSystemInfoSync();
var _this;
var app = getApp();
var door = require('../../utils/door.js');
var head = require('../../utils/customHead.js');

export default {
	data() {
		return {
			SHOW: false,
			FADE: -1,
			poster:{
				mask:true,
				maskTapClose:true,
				image:'https://jlmkkj.oss-accelerate.aliyuncs.com/upload/config/000/000/020/60209b5a4342e541.png'
			},
			
			config: {},
			doorList: [],
			openId: '',
			openDoll: {},
			closeDoll: false,
			location: true,
			openSetting: true,
			redirect: '',
			firstShow: true,
			userLocation: {},
			timer: null,
			locationTimer: null,
			door_share_id: '',
			show_openDoor: false,
			open_door: ['开启蓝牙，才能为您自动开门哦！', '正在实时搜索周边门禁自动开门中...', '开门成功，10秒后将再次搜索周边门禁', '本次自动开门已成功'],
			open_door_index: 0,
			open_door_type: false,
			is_automatic_open_door: false,
			//自动开门
			openBlueNum: true,
			size: 14,
			hide: false,
			addMySmallProgram: true,
			is_btn: false,
			account_height: 0,
			myaudio: '',
			tabbar: {},
			showBackIcon: false,
			options: '',
			pageOpenTimes: 0,
			scrollToTop: false,
			scene: 0,
			auiPoster: {
				mask: true,
				maskTapClose: false,
				image: 'https://xbjz1.oss-cn-beijing.aliyuncs.com/upload/default/share.png'
			  }
		};
	},
	onShareAppMessage: function() {
		var id = app.globalData.userInfo.wxapp_openid;
		let pageLink = '/pages/plat_menu/index?openId=' + id
		pageLink = common.addShareParam(pageLink)
		return {
			title: _this.config.config.wechat_name,
			path: pageLink
		};
	},
	onUnload: function() {
		// 页面关闭
		if (this.open_door_type && this.doorList.length > 0) {
			//关闭蓝牙
			wx.stopBluetoothDevicesDiscovery({
				success: function() {
					wx.closeBluetoothAdapter({
						success: function() {}
					});
				}
			});
		}

		this.hide = true;
		this.door_share_id = '';
		this.openBlueNum = false;
		clearInterval(this.timer);
		clearInterval(this.locationTimer);
		console.log('获取用户位置清除了', this.locationTimer);
		
		// #ifdef H5
		uni.removeStorageSync('plat_index_share')
		// #endif
		
		uni.$off('pageShow')
	},
	onHide: function() {
		// 页面隐藏
		this.hide = true;
		this.door_share_id = '';
		this.openBlueNum = false; 
		clearInterval(this.timer);
		clearInterval(this.locationTimer);
		console.log('获取用户位置清除了', this.locationTimer);
	},
	onShow: function() {
		common.editTabbar('', function(tabbar){
			_this.tabbar = tabbar
		});
		app.checkIsHome('/' + (_this.__route__ ? _this.__route__ : _this.route));
		this.hide = false;
		this.openBlueNum = true;

		if (app.globalData.is_login && typeof _this.pageLoaded != 'undefined') {
			console.log('show获取门禁列表');

			if (wx.getStorageSync('auto_door_open') && wx.getStorageSync('auto_door_open') == 0) {
				_this.open_door_type = !wx.getStorageSync('auto_door_open') || wx.getStorageSync('auto_door_open') == 0 ? false : true;
			}

			door.getDoorList(_this);
		}
		
		

		if (_this.pageLoaded === true && _this.pageRedirect) {
			common.setMainColor(_this);
			common.editTabbar('', function(tabbar){
				_this.tabbar = tabbar
			});
			_this.pageLoaded = false;
			console.log('第二次进入首页');
		} else if (typeof _this.pageLoaded == 'undefined') {
			_this.pageLoaded = true;
			console.log('第一次进入首页111');
		}
		
		// #ifdef  MP-WEIXIN
		wx.showShareMenu({
			withShareTicket: true
		});
		// 获取用户的实际位置，腾讯经纬度

		if (_this.timer != null) {
			clearInterval(_this.timer);
		}

		_this.timer = setInterval(() => {
			wx.getSetting({
				success: res => {
					// console.log('2222222222结束询问是否有权限', res)
					if (res.authSetting['scope.userLocation'] != undefined) {
						clearInterval(_this.timer);
					}

					if (res.authSetting['scope.userLocation'] == true) {
						if (_this.locationTimer != null) {
							clearInterval(_this.locationTimer);
						}

						_this.locationTimer = setInterval(() => {
							var pages = getCurrentPages();
							console.log('当前页面栈', pages);

							if (pages.length > 0 && pages[pages.length - 1].route != 'pages/plat_menu/index') {
								console.log('不是首页，清除获取位置定时器');
								clearInterval(_this.timer);
								clearInterval(_this.locationTimer);
							}

							wx.getLocation({
								type: 'gcj02',
								success: res => {
									_this.userLocation = {
										lng: res.longitude,
										lat: res.latitude,
										type: 'gcj02'
									}

									common.location_report(res.longitude, res.latitude, 'gcj02');
									console.log('获取用户位置444444444', res);
									wx.setStorageSync('userLocation', _this.userLocation);
								}
							});
						}, 60000);
					}
				}
			});
		}, 1000);
		// #endif
		
		_this.pageOpenTimes++;
		uni.$emit('pageShow', _this.pageOpenTimes)
		
		// #ifdef H5
		if (_this.pageOpenTimes > 1) {
			let shareData = uni.getStorageSync('index_share_data')
			if (shareData) {
				setWxShare(JSON.parse(shareData))
			}
		}
		// #endif
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
		_this = this;
		_this.options = options;
		if (options.scene) {
			_this.scene = options.scene
		}
		// #ifdef H5
			console.log('准备跳小程序页', _this.options);
			common.webToMiniapp(_this.route, options, 'redirect')
		// #endif
		
		common.post("Shop_new&a=dialog_is",{},data => {
			if(data.status == 1){
				_this.SHOW = true;
				_this.FADE = 1;	
			}
		})
		
		common.setMainColor(_this, function(config) {
			
			_this.door_share_id = options.door_share_id && options.door_share_id != '' ? options.door_share_id : '';
			_this.myaudio = wx.createInnerAudioContext();
			//不是从个人中心拒绝授权后进入
			if (!options.no_auth) {
				app.globalData.door_share_id = options.door_share_id && options.door_share_id != '' ? options.door_share_id : '';
			}
			// #ifdef  MP-WEIXIN
			wx.showShareMenu({
				withShareTicket: true
			});
			// #endif
			
			uni.setNavigationBarTitle({
			    title: config.config.wechat_name
			});
		});
		
		
		_this.redirect = options.redirect ? options.redirect : '';

		// 获取详情
		order_detail(options);

		// #ifdef MP-WEIXIN
		// 判断版本号是否大于2.5.2
		if (!options.redirect) {
			const version = systemInfo.SDKVersion;
			console.log('444444444444', compareVersion(version, '2.5.2'));

			if (compareVersion(version, '2.5.2') < 0) {
				// 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
				wx.showModal({
					title: common.changeTxt('提示'),
					content: common.changeTxt('当前微信版本过低，无法使用部分功能，请升级到最新微信版本后重试。'),
					showCancel: false
				});
			}
		}
		// #endif
	},
	components: {
		indexTemplate,
		collectMiniapp
	},
	methods: {  
		_clickFn(e){
			_this.FADE = 0;
			var _hidetimer = setTimeout(()=>{
				_this.SHOW = false;
				_this.FADE = -1;
				clearTimeout(_hidetimer);
			},100)
		},
		
		
		returnTop (e) {
			console.log('点击回到顶部')
			this.scrollToTop = true
		},
		setTabbar (e) {
			console.log('tabbar1')
			console.log(e)
			if (e.tabbar) {
				// this.tabbar = e.tabbar
			} else {
				this.scrollToTop = false
			}
		}
	}
};


const order_detail = opt => {
		if (opt.redirect) {
			console.log('首页是否需要跳转7777', opt);
			var tabTimer = setInterval(() => {
				console.log('首页是否需要跳转888', app.globalData.tabBar);
				if (app.globalData.tabBar && app.globalData.tabBar.list.length > 0) {
					clearInterval(tabTimer);
					var route = '/' + (_this.__route__ ? _this.__route__ : _this.route);
					console.log('首页是否需要跳转9', route);
					if (route != app.globalData.tabBar.list[0].pagePath) {
						app.globalData.homeRedirect = {
							type: opt.redirect,
							url: opt.redirect == 'page' ? opt.page : opt.webview_url,
							title: opt.webview_title ? opt.webview_title : ''
						};
						return;
					} else {
						app.globalData.homeRedirect = '';
					}
	
					console.log('首页是否需要跳转9999999999', opt);
	
					if (opt && opt.redirect == 'webview') {
						console.log('opt.webview', 'webview');
						common.parseUrl(decodeURIComponent(opt.webview_url), '', false, opt.webview_title ? decodeURIComponent(opt.webview_title) : '');
					} else if (opt.redirect == 'page') {
						var tmppage = decodeURIComponent(opt.page);
	
						if (tmppage.indexOf('/') !== 0) {
							tmppage = '/' + tmppage;
						}
	
						console.log('opt.page', tmppage);
						wx.navigateTo({
							url: tmppage
						});
					}
	
					_this.pageRedirect = opt.redirect;
				}
			}, 100);
		}
	};
	

const compareVersion = (v1, v2) => {
	v1 = v1.split('.');
	v2 = v2.split('.');
	const len = Math.max(v1.length, v2.length);

	while (v1.length < len) {
		v1.push('0');
	}

	while (v2.length < len) {
		v2.push('0');
	}

	for (let i = 0; i < len; i++) {
		const num1 = parseInt(v1[i]);
		const num2 = parseInt(v2[i]);

		if (num1 > num2) {
			return 1;
		} else if (num1 < num2) {
			return -1;
		}
	}

	return 0;
};
// 微信h5分享
	const setWxShare = (data) => {
		let pageLink = `${common.requestDomain}packapp/${common.wxapp_type}/`;
		pageLink = common.addShareParam(pageLink)
		let shareWxLink = pageLink;
		var shareData = {
			title: data.h5_title,
			desc: data.h5_content,
			sendFriendLink: shareWxLink,
			share_img: data.h5_img
		};
		common.setWxShare(shareData);
	};
</script>
<style>
@import './index.css';

@import url("aui-poster/common/aui/css/aui.css");
@import url("aui-poster/common/aui/css/aui.iconfont.css");

uni-page-body{
	padding-bottom: 0 !important;
	overflow-x: hidden;
}
.page-wrapper{
	padding-bottom: 98rpx;
	padding-bottom: calc(98rpx + env(safe-area-inset-bottom));
	padding-bottom: calc(98rpx + constant(safe-area-inset-bottom));
	height: 100%;
	box-sizing: border-box;
	overflow-x: hidden;
}


/*poster 广告弹窗*/
	.aui-poster{width: 100vw; height: 100vh; position: fixed; top: 0; left: 0; z-index: 998;}
	.aui-poster .aui-mask{z-index: 996; position: absolute;}
	.aui-poster-main{width: 80%; opacity: 0; position: fixed; top: -50vh; left: 10%; z-index: 999;}
	.aui-poster-in .aui-poster-main{animation: aui-slide-up_to_middle .3s ease-out forwards;}
	.aui-poster-out .aui-poster-main{animation: aui-slide-middle_to_up .2s ease-out forwards;}
	.aui-poster-main .aui-poster-img{width: 100%; pointer-events: auto; position: relative; z-index: 999;}
	.aui-poster-main .aui-poster-close{width: 30px; position: absolute; top: -webkit-calc(100% - 10px); top: calc(100% - 10px); left: 50%; -moz-transform: translate(-50%,0); -ms-transform: translate(-50%,0); -webkit-transform: translate(-50%,0); transform: translate(-50%,0); z-index: 998;}

</style>
